<template>
	<view class="web-wrap">
		<view class="web-cont">
			<!-- 雷达扫码开始 -->
			<radar :imageUrl="imageUrl"></radar>
			<!-- 雷达扫码结束 -->

			<view class="web-text">
				<view>连接WiFi并输入密码</view>
			</view>
		</view>

		<view class="web-item">
			<view class="web-title flex">
				<view>正在发现网络</view>
				<uni-load-more class="icon-zq" :status="status" :content-text="contentText" iconSize="18" />
			</view>
			<view class="item-box">
				<view class="item flex_s" @click="handleShowWifiPassInput(wifi)" v-for="wifi in wifiList"
					:key="wifi.SSID">
					<view class="item-left">{{ wifi.SSID }}</view>
					<view class="item-right flex">
						<view v-if="wifi.connected">已连接</view>
						<view v-else>未连接</view>
						<image class="item-icon-s" src="/static/image/icon-suo.png"></image>
						<image class="item-icon-w" src="/static/image/icon-wifi.png"></image>
					</view>
				</view>
			</view>
		</view>

		<PopupInput ref="PopupInput" @confirm="handleInputConfirm" :title="title"></PopupInput>

	</view>
</template>

<script>
	import BleService from './cs.js';
	import PopupInput from '@/componets/PopupInput.vue';
	import radar from '@/componets/radar.vue';
	import xBlufi from '@/utils/blufi/xBlufi.js'
	import $wxBlufiImpl from '@/utils/blufi/xBlufi-wx-impl.js';
	export default {
		components: {
			PopupInput,
			radar
		},
		data() {
			return {
				title: '输入WiFi密码',
				imageUrl: 'https://be.coucoq.cn/jueli/static/2025/01/07/65f82df0-96c5-4169-b1e0-e821b1c9cc8a.png', //wifi背景图
				status: 'loading', //加载中样式
				contentText: '', //加载中文字
				password: '',
				wifiList: [],
				connectedWifi: {},
				changeWifiInfo: {},
				deviceId: '', // 蓝牙
				services: '', // 蓝牙服务ID
				readyservices: '', // 蓝牙特征ID
				noty: '', // 蓝牙特征ID
			}
		},
		onShow() {
			// this.getWifiList();        //获取周围wifi
			// this.onGetWifiList();      //监听获取wifi列表
			this.onGetWifiList();
		},
		onLoad(opts) {
			this.deviceId = opts.deviceId || '';
			this.services = opts.services || '';
			this.readyservices = opts.readyservices || '';
			this.noty = opts.noty || '';
			this.deviceId = decodeURIComponent(this.deviceId.replace(/%25/g, '%'));

			console.log('opts==readyservices==', opts.readyservices, 'noty==', opts.noty)
			// xBlufi.initXBlufi(1);
			// $wxBlufiImpl.init(this.deviceId);
			// // 读取当前设备所连wifi信息
			// this.sendCommandAndReceiveResponse();

			uni.onBluetoothAdapterStateChange((res) => {
				console.log('蓝牙适配器已启用', res);
			});
			this.startWifi();
			this.getWifiList(); //获取周围wifi

		},
		methods: {
			// 输入完密码确定后
			handleInputConfirm(pass) {
				// 这里添加你想要执行的代码
				console.log('知道了', pass);
				this.password = pass
				this.connectWifi()
			},
			/** 1.初始化启动wifi */
			startWifi() {
				let that = this;
				return new Promise((resolve, reject) => {
					uni.startWifi({
						success: (res) => {
							// console.log('启动wifi 成功', res)
							resolve(true)
							that.config.Toast('初始化成功');
						},
						fail: (err) => {
							console.error('启动wifi 失败', err.errMsg)
							uni.showModal({
								content: 'wifi连接失败',
								showCancel: false
							})
							reject(new Error(err))
						},
					})
				})
			},
			//2.获取周围wifi列表
			async getWifiList() {
				const hasStart = await this.startWifi();
				// console.log('初始化启动wifi==',hasStart)
				if (hasStart !== true) return
				uni.getWifiList({
					success: (res1) => {
						console.log('获取wifi列表命令发送 成功', res1)
						this.wifiList = res1
						this.onGetWifiList(); //监听获取wifi列表
					},
					fail: (err) => {
						console.error('获取wifi列表 失败', err.errMsg)
						uni.showModal({
							content: 'wifi连接失败',
							showCancel: false
						})
					},
				})
			},

			/** 监听获取wifi列表 */
			onGetWifiList() {
				let that = this;
				wx.onGetWifiList((res) => {
					// console.log('是否执行1  res===',res);

					let {
						wifiList
					} = res;

					// 过滤SSID为空的数据
					wifiList = wifiList.filter(wifi => wifi.SSID);

					// 过滤同名WiFi信号，并保留信号强度最强的
					let filterList = wifiList.reduce((result, item) => {
						let index = result.findIndex((v) => {
							return v.SSID === item.SSID;
						});
						if (index < 0) {
							result.push(item);
						} else if (item.signalStrength > result[index].signalStrength) {
							result[index] = item;
						}
						return result;
					}, []);

					// 标记已连接的WiFi
					filterList = filterList.map(wifi => ({
						...wifi,
						connected: wifi.SSID === that.connectedWifi.SSID
					}));

					// 将已连接的WiFi排序到第一位
					let connectedWifiIndex = filterList.findIndex(wifi => wifi.connected);
					if (connectedWifiIndex > -1) {
						let [connectedWifi] = filterList.splice(connectedWifiIndex, 1);
						filterList.unshift(connectedWifi);
					}

					// console.log('过滤同名后并排序', filterList);
					that.wifiList = filterList;
				});
			},
			// 显示wifi密码输入框
			handleShowWifiPassInput(row) {
				this.changeWifiInfo = row
				this.$refs.PopupInput.open();
			},
			/** 连接某个 Wi-Fi */
			// async connectWifi() {
			// 	let that = this;
			// 	let apName = that.changeWifiInfo.SSID;
			// 	let password = that.password;
			// 	// const data = `${apName}|${password}`;
			// 	// const buffer = new ArrayBuffer(data.length);
			// 	// const dataView = new Uint8Array(buffer);
			// 	// for (let i = 0; i < data.length; i++) {
			// 	// 	dataView[i] = data.charCodeAt(i);
			// 	// }
			// 	// console.log(data, 'data')
			// 	// console.log(buffer, 'buffer')
			// 	// console.log(dataView, 'dataView')
			// 	// uni.writeBLECharacteristicValue({
			// 	// 	deviceId: that.deviceId,
			// 	// 	serviceId: that.services,
			// 	// 	characteristicId: that.readyservices,
			// 	// 	value: buffer,
			// 	// 	success: function(res) {
			// 	// 		console.log('配网指令发送成功', res);
			// 	// 		if (res.errCode == 0) {
			// 	// 			that.config.Toast('配网成功~')
			// 	// 			// that.startNotice()
			// 	// 		}
			// 	// 	},
			// 	// 	fail: function(err) {
			// 	// 		console.error('配网指令发送失败', err);
			// 	// 	}
			// 	// });
			// 	// console.log('wifi名称==', apName, 'wifi密码===', password);

			// 	// 构建配网指令					
			// 	let command = that.buildConfigCommand(apName, password);

			// 	console.log('buffer==', command)

			// 	console.log('构建配网指令11', 'Id==', that.deviceId, '服务services==', that.services, '特征值==', that
			// 		.readyservices, 'noty==', that.noty)

			// 	uni.writeBLECharacteristicValue({
			// 		deviceId: that.deviceId,
			// 		serviceId: that.services, // 蓝牙设备的服务ID
			// 		characteristicId: that.readyservices, // 蓝牙设备的特征ID
			// 		value: command,
			// 		success: function(res) {
			// 			console.log('配网指令发送成功', res);
			// 			if (res.errCode == 0) {
			// 				that.config.Toast('配网成功~')
			// 				that.startNotice()
			// 			}
			// 		},
			// 		fail: function(err) {
			// 			console.error('配网指令发送失败', err);
			// 		}
			// 	});
			// },

			// async connectWifi() {
			// 	if (!this.changeWifiInfo.SSID || !this.password) {
			// 		this.config.Toast('请输入 SSID 和密码');
			// 		return;
			// 	}

			// 	try {
			// 		this.status = 'configuring';
			// 		this.message = '正在配网...';

			// 		// 创建 BluFi 服务实例
			// 		const bleService = new BleService();

			// 		// 设置设备信息
			// 		bleService.deviceId = this.deviceId;
			// 		bleService.serviceId = this.services;
			// 		bleService.writeCharacteristicId = this.readyservices;
			// 		bleService.notifyCharacteristicId = this.noty;

			// 		// 开始配网
			// 		const result = await bleService.startConfig(
			// 			this.changeWifiInfo.SSID,
			// 			this.password
			// 		);

			// 		if (result) {
			// 			this.config.Toast('配网成功');
			// 			this.status = 'idle';
			// 			this.message = '设备已连接';
			// 		} else {
			// 			throw new Error('配网失败');
			// 		}

			// 	} catch (error) {
			// 		console.error('配网错误:', error);
			// 		this.status = 'idle';
			// 		this.message = '配网失败：' + error.message;
			// 		this.config.Toast(this.message);
			// 	}
			// },

			// 封装 BLUFI 数据
			stringToUint8Array(str) {
				const arr = [];
				for (let i = 0; i < str.length; i++) {
					arr.push(str.charCodeAt(i));
				}
				return new Uint8Array(arr);
			},
			buildBlufiData(ssid, password) {
				// 将字符串转换为 Uint8Array
				// 构建 BLUFI 数据
				const ssidData = this.stringToUint8Array(ssid);
				const passwordData = this.stringToUint8Array(password);

				const data = new Uint8Array([
					0x01, // Type: Wi-Fi configuration
					0x00, // Subtype: SSID
					ssid.length, // SSID length
					...ssidData, // SSID data
					0x01, // Subtype: Password
					password.length, // Password length
					...passwordData // Password data
				]);

				return data.buffer;
			},

			connectWifi() {
				const that = this;
				const apName = that.changeWifiInfo.SSID;
				const password = that.password;
				xBlufi.notifySendRouterSsidAndPassword({
					ssid: apName,
					password: password
				})


			},
			// 构建 Blufi 数据包
			buildBlufiPacket(type, data) {
				const header = new Uint8Array([type, 0x00, 0x00]); // Type, Seq, FrameCtrl
				const dataLength = new Uint8Array([(data.length >> 8) & 0xFF, data.length & 0xFF]);
				const temp = new Uint8Array([...header, ...dataLength, ...data]);
				console.log(temp, 'temp')
				const crc = this.calculateCRC16(temp);
				const crcBuffer = new Uint8Array([(crc >> 8) & 0xFF, crc & 0xFF]);
				return new Uint8Array([...temp, ...crcBuffer]).buffer;
			},


			// 构建配网指令
			buildConfigCommand(apName, password) {
				let commandLength = 2 + 32 + 32; // 2 字节命令码 + 32 字节 AP 名 + 32 字节密码
				let buffer = new ArrayBuffer(commandLength);
				let view = new DataView(buffer);

				// 设置命令码
				view.setUint16(0, 0x008D, true); // 命令码 0x008D

				// 设置 AP 名
				let apNameBytes = this.stringToBytes(apName, 32); // 转换 AP 名为字节数组并填充
				for (let i = 0; i < 32; i++) {
					view.setUint8(2 + i, apNameBytes[i]);
				}

				// 设置密码
				let passwordBytes = this.stringToBytes(password, 32); // 转换密码为字节数组并填充
				for (let i = 0; i < 32; i++) {
					view.setUint8(34 + i, passwordBytes[i]);
				}

				return buffer;
			},
			// 将字符串转换为字节数组并填充
			stringToBytes(str, length) {
				let bytes = [];
				for (let i = 0; i < str.length; i++) {
					bytes.push(str.charCodeAt(i));
				}

				// 如果字节数组小于指定长度，填充 '\0' (0x00)
				while (bytes.length < length) {
					bytes.push(0);
				}

				return new Uint8Array(bytes);
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			// 接受消息通知
			startNotice() {
				var that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能  
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.services,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.noty, //第一步 开启监听 notityid  第二步发送指令 write
					success(res) {
						console.log('接受消息成功222', res)
						// 接受设备响应
						uni.onBLECharacteristicValueChange((res2) => {
							console.log('收到设备反馈:', res2);
							console.log(that.ab2hex(res2.value))
							// 根据反馈判断配网是否成功
						});
					},
					fail(err) {
						console.log('接消息失败222', err)
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.web-wrap {
		.web-cont {
			background: #E0DAC9;

			.web-text {
				line-height: 49rpx;
				font-size: 30rpx;
				text-align: center;
				margin-top: 80rpx;
			}
		}

		.web-item {
			background-image: linear-gradient(to bottom, #E0DAC9, rgba(243, 238, 230, 0.1));
			margin: auto;
			padding: 50rpx 0;
			font-size: 30rpx;

			.web-title {
				width: 90%;
				margin: 20rpx auto;

				.icon-zq {
					margin-left: 10rpx;
				}
			}

			.item-box {
				width: 90%;
				margin: auto;
				background: #fff;
				border-radius: 15rpx;

				.item {
					line-height: 100rpx;
					border-bottom: 1rpx solid #f5f5f5;
					padding: 0 40rpx;
					color: #666666;
				}

				.item-left {}

				.item-right {
					.item-icon-s {
						width: 16rpx;
						height: 22rpx;
						margin: 0 23rpx 0 38rpx;
					}

					.item-icon-w {
						width: 30rpx;
						height: 21rpx;
					}
				}
			}
		}
	}
</style>